package com.example.demo.controller;

import com.example.demo.req.ChatRequest;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Map;

@RestController
@RequestMapping("/api/deepseek")
public class DeepSeekController {
    @Autowired
    private OpenAiChatModel chatModel;


    @PostMapping("chat")
    public Map<String, String> generate(@RequestBody ChatRequest request) {
        return Map.of("generation", this.chatModel.call(request.getQuestion()));
    }

    @PostMapping(value = "chat-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> generateStream(@RequestBody ChatRequest request) {
        Prompt prompt = new Prompt(new UserMessage(request.getQuestion()));

        return this.chatModel.stream(prompt)
                .map(chatResponse -> {
                    // 根据调试结果，使用正确的路径获取内容
                    String content = chatResponse.getResult().getOutput().getText();
                    // 防止content为null时发送null事件
                    if (content == null) {
                        return null;
                    }
                    // 创建符合HTML页面期望的JSON格式
                    String jsonData = "{\"result\":{\"output\":{\"content\":\"" + content.replace("\"", "\\\"") + "\"}}}";
                    return ServerSentEvent.builder(jsonData).build();
                })
                // 过滤掉可能产生的null事件
                .filter(sse -> sse != null)
                // 在流结束时发送一个 [DONE] 事件
                .concatWithValues(ServerSentEvent.builder("[DONE]").build());
    }
}
